<?php

namespace app\admin\controller;

use app\models\{Gsdselect, Lists, Peizhi, Ecsource, Laiyuan, Tags, ExphoneCopy, CopyList, Liaotian};
use think\Db;
use think\Validate;
use app\facade\Redis;
use think\facade\Log;
use think\facade\App;



class Lista extends Base
{

    public function excall()
    {
        if ($this->request->isAjax()) {
            $model = new ExphoneCopy();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['isdel', '=', 1];
            if (!empty($post['title'])) {
                $where[] = ['phone|channel', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['created'])) {
                $where[] = ['daorutime', '=', $post['created']];
            }
            if (!empty($post['copyid'])) {
                $where[] = ['copyid', '=', $post['copyid']];
            }
            if (!empty($post['channel'])) {
                $where[] = ['channel', '=', $post['channel']];
            }
            if (!empty($post['yxtags'])) {
                $value = explode(',', $post['yxtags']);
                // 将数组转换为正则表达式
                $regexp = implode('|', array_map(function ($value) {
                    return preg_quote($value, '/'); // 转义特殊字符
                }, $value));
                $where[]   = ['yxtags', 'REGEXP', $regexp];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            foreach ($list as $row) {
                $lypinpai = (new Peizhi())->where(['type' => $row['type']])->column('pinpai') ?? [];
                $row['lypinpai'] = implode(',', $lypinpai);
                $lympinpai = (new Peizhi())->where(['type' => $row['typem']])->column('pinpai') ?? [];
                $row['nnpinpai'] = implode(',', $lympinpai);
                $types = explode(',', $row['types']);
                $pinpai = (new Peizhi())->where(['type' => $types])->column('pinpai') ?? [];
                $row['pinpai'] = implode(',', $pinpai);
                $istype = explode(',', $row['istype']);
                $ispinpai = (new Peizhi())->where(['type' => $istype])->column('pinpai') ?? [];
                $row['ispinpai'] = implode(',', $ispinpai);
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            if ($this->request->admin['id'] != 1) {
                $laiyuan = (new ExphoneCopy())->where(['istype' => $this->request->admin['groups']])->group('channel')->column('channel') ?? [];
                $yxtags = (new ExphoneCopy())->where(['istype' => $this->request->admin['groups']])->group('yxtags')->column('yxtags') ?? [];
            } else {
                $laiyuan = (new ExphoneCopy())->group('channel')->column('channel') ?? [];
                $yxtags = (new ExphoneCopy())->group('yxtags')->column('yxtags') ?? [];
            }
            $laiyuan = array_filter($laiyuan);
            $yxtags = array_filter($yxtags) ?? [];
            $yxtags = implode(',', $yxtags);
            $yxtags = explode(',', $yxtags) ?? [];
            $yxtags = array_unique($yxtags) ?? [];
            $copylist = (new CopyList())->field('id,name')->select();
            return view(null, ['laiyuan' => $laiyuan, 'yxtags' => $yxtags, 'copylist' => $copylist]);
        }
    }


    public function excall_del()
    {
        $data = input();
        if (empty($data['id'])) {
            return json(['code' => 1, 'data' => [], 'msg' => '请选择项目内容']);
        }
        $model = new ExphoneCopy();
        $have = $model->where(['id' => $data['id']])->find();
        if (empty($have)) {
            return json(['code' => 1, 'data' => [], 'msg' => '项目不存在']);
        }
        Db::startTrans();
        try {
            $model->where(['id' => $data['id']])->update(['isdel' => 2]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
        }
        return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
    }


    public function index()
    {
        if ($this->request->isAjax()) {
            $model = new Lists();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['created'])) {
                $where[] = ['created', '>= time', $post['created'] . ' 00:00:00'];
                $where[] = ['created', '<= time', $post['created'] . ' 23:59:59'];
            }
            if (!empty($post['createds'])) {
                $where[] = ['createds', '>= time', $post['createds'] . ' 00:00:00'];
                $where[] = ['createds', '<= time', $post['createds'] . ' 23:59:59'];
            }
            if (!empty($post['title'])) {
                $where[] = ['name|phone|othertel', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['adv_id'])) {
                $where[] = ['adv_id|cid|promotion_id|videoid', '=', $post['adv_id']];
            }
            if (!empty($post['address'])) {
                $where[] = ['address', 'like', '%' . $post['address'] . '%'];
            }
            if (!empty($post['isexcel'])) {
                $where[] = ['isexcel', 'like', '%' . $post['isexcel'] . '%'];
            }
            if (!empty($post['type'])) {
                $where[] = ['type', '=', $post['type']];
            }
            if (!empty($post['repeats'])) {
                $where[] = ['repeats', '=', $post['repeats']];
            }
            if (!empty($post['allocation'])) {
                $where[] = ['allocation', '=', $post['allocation']];
            }
            if (!empty($post['youxiao'])) {
                $where[] = ['youxiao', '=', $post['youxiao']];
            }
            $where[] = ['isdel', '=', 1];
            $isshow = 1;
            if ($this->request->admin['id'] != 1) {
                $where[] = ['type', 'in', $this->request->admin['groups']];
                $isshow = 2;
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;

            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            foreach ($list as $row) {
                $row['ly_name'] = config()['config']['laiyuan'][$row['clue_source']] ?? '';
                if (!empty($row['fplaiyuan'])) {
                    $row['fplaiyuan_name'] = (new Ecsource())->where(['type' => $row['type'], 'ecid' => $row['fplaiyuan']])->value('ecname') ?? '无';
                } else {
                    $row['fplaiyuan_name'] = '无';
                }
                $row['show'] = 1;
                if ($this->request->admin['id'] != 1) {
                    $row['adv_id'] = '';
                    $row['promotion_id'] = '';
                    $row['videoid'] = '';
                    $row['pingtai'] = '';
                    $row['ly_name'] = '';
                    $row['fplaiyuan_name'] = '';
                    $row['show'] = 2;
                    // $row['phone'] = substr_replace($row['phone'], '****', 3, 4);
                }
                $row['phone'] = trim($row['phone']);
                $row['address'] = trim($row['address']);
                if (empty($row['address']) && !empty($row['phone'])) {
                    try {
                        $getgsd['province'] = '';
                        $getgsd['city'] = '';
                        $subphone = substr($row['phone'], 0, 7);
                        $subplist = (new Gsdselect())->where('phone', $subphone)->find();
                        if (!empty($subplist)) {
                            $getgsd['province'] = $subplist['province'] ?? '';
                            $getgsd['city'] = $subplist['city'] ?? '';
                        }
                        if (!empty($getgsd['province']) && !empty($getgsd['city'])) {
                            $location = trim($getgsd['province']) . ' ' . trim($getgsd['city']);
                        }
                        if (empty($getgsd['province']) || empty($getgsd['city'])) {
                            $getgsd = api_curlphone($row['phone']);
                            if (!empty($getgsd['data']['prov']) && !empty($getgsd['data']['city'])) {
                                $location = trim($getgsd['data']['prov']) . ' ' . trim($getgsd['data']['city']);
                            }
                        }
                        if (!empty($location)) {
                            $model->where('id', $row['id'])->update(['address' => $location]);
                            $row['address']  = $location;
                        }
                    } catch (\Exception $e) {
                    }
                }
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count, 'isshow' => $isshow]);
        } else {
            $pinpai = (new Peizhi())->field('type,id,pinpai');
            if ($this->request->admin['id'] != 1) {
                $pinpai = $pinpai->where(['type' => $this->request->admin['groups']]);
            }
            $pinpai = $pinpai->where('status', 1)->select();
            $quanx = 2;
            if ($this->request->admin['id'] == 1) {
                $quanx = 1;
            }
            return view(null, ['pinpai' => $pinpai, 'quanx' => $quanx]);
        }
    }

    public function laiyuan()
    {
        if ($this->request->isAjax()) {
            $model = new Laiyuan();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['pe.status', '=', 1];
            if ($this->request->admin['id'] != 1) {
                $where[] = ['la.type', 'in', $this->request->admin['groups']];
            }
            if (!empty($post['type'])) {
                $where[] = ['la.type', '=', $post['type']];
            }
            if (!empty($post['title'])) {
                $where[] = ['la.yyname|la.ly', 'like', '%' . $post['title'] . '%'];
            }
            $count = $model->alias('la')->leftJoin('peizhi pe', 'pe.type = la.type')->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->field('la.*,pe.pinpai as type_name')->alias('la')->leftJoin('peizhi pe', 'pe.type = la.type')->where($where)->order("id desc")->limit($limit)->page($page)->select();
            foreach ($list as $row) {
                //$row['type_name'] = (new Peizhi())->where(['type' => $row['type']])->value('pinpai') ?? '未知';
                $row['ly_name'] = $row['ly'] ?? '';
                $row['ec_name'] = (new Ecsource())->where(['type' => $row['type'], 'ecid' => $row['ecRcm']])->value('ecname') ?? '未知';
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            $peizhis = (new Peizhi());
            if ($this->request->admin['id'] != 1) {
                $peizhis = $peizhis->where(['type' => $this->request->admin['groups']]);
            }
            $peizhis = $peizhis->where('status', 1)->select();
            foreach ($peizhis as $peizhi) {
                //reids设置1小时更新一次
                $rdsnames = 'peizhiupdates' . $peizhi['id'];
                $rdspeizhi = Redis::get($rdsnames);
                if ($rdspeizhi) {
                    continue;
                }
                $url = "https://open.workec.com/v2/customer/getChannelSource";
                list($returnCode, $returnContent) = doGet($peizhi['cid'], $peizhi['appId'], $peizhi['appSecret'], $url, []);
                $rjson = json_decode($returnContent, true) ?? [];
                Log::write($rjson, 'getdata');
                if (empty($rjson['data'])) {
                    $rjson['data'] = [];
                }
                $save = [];
                foreach ($rjson['data'] as $js) {
                    $save[] = [
                        'type' => $peizhi['type'],
                        'ecid' => $js['id'],
                        'ecname' => $js['name'],
                        'ecgroupId' => $js['groupId'],
                        'ecgroupName' => $js['groupName'],
                        'created' => date('Y-m-d H:i:s')
                    ];
                }
                Db::startTrans();
                try {
                    (new Ecsource())->where(['type' => $peizhi['type']])->delete();
                    (new Ecsource())->allowfield(true)->saveAll($save);
                    Db::commit();
                    Redis::setex($rdsnames, 120, 120);
                } catch (\Exception $e) {
                    Db::rollback();
                    Log::write('----EC类目更新开始-----', 'getdata');
                    Log::write($e->getMessage(), 'getdata');
                    Log::write('----EC类目更新结束-----', 'getdata');
                }
            }
            return view(null, ['pinpai' => $peizhis]);
        }
    }



    public function laiyuan_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'type' =>  'require',
                'ly' => 'require',
                'ecRcm' => 'require'
            ], [
                'type.require' => '品牌不能为空',
                'ly.require' => '平台来源不能为空',
                'ecRcm.require' => 'EC来源不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' => $validate->getError()]);
            }
            if ($this->request->admin['id'] != 1 && !in_array($data['type'], $this->request->admin['groups'])) {
                return json(['code' => 1, 'msg' => '无品牌权限']);
            }
            //查询是否已经添加
            $rowid = (new Laiyuan())->where(['type' => $data['type'], 'ly' => $data['ly'], 'ecRcm' => $data['ecRcm']])->find();
            if ($data['id'] > 0) {
                if (!empty($rowid['id']) && $data['id'] != $rowid['id']) {
                    return json(['code' => 1, 'msg' => '广告主对应ec来源已添加']);
                }
                $res = (new Laiyuan())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                if (!empty($rowid['id'])) {
                    return json(['code' => 1, 'msg' => '广告主对应ec来源已添加']);
                }
                $res = (new Laiyuan())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败,请重试']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Laiyuan())->where('id', $id)->find();
            $pinpai = (new Peizhi())->field('type,id,pinpai');
            if ($this->request->admin['id'] != 1) {
                $pinpai = $pinpai->where(['type' => $this->request->admin['groups']]);
            }
            $pinpai = $pinpai->where('status', 1)->select();
            $ptlaiyuan = config()['config']['laiyuan'] ?? [];
            $eclaiyuan = (new Ecsource())->where(['type' => $row['type']])->select() ?? [];
            return view('', ['row' => $row, 'pinpai' => $pinpai, 'ptlaiyuan' => $ptlaiyuan, 'eclaiyuan' => $eclaiyuan]);
        }
    }

    public function laiyuan_del()
    {
        $data = input();
        if (empty($data['id'])) {
            return json(['code' => 1, 'data' => [], 'msg' => '请选择项目内容']);
        }
        $model = new Laiyuan();
        $have = $model->where('id', $data['id'])->find();
        if (empty($have)) {
            return json(['code' => 1, 'data' => [], 'msg' => '项目不存在']);
        }
        if ($this->request->admin['id'] != 1 && !in_array($have['type'], $this->request->admin['groups'])) {
            return json(['code' => 1, 'msg' => '无品牌权限']);
        }
        Db::startTrans();
        try {
            $model->where(['id' => $data['id']])->delete();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
        }
        return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
    }

    public function lista_status()
    {
        $data = input();
        switch ($data['status']) {
            case 'isdel':
                if (empty($data['id']) || (is_array($data['id']) && count($data['id']) <= 0)) {
                    return json(['code' => 1, 'data' => [], 'msg' => '请选择项目内容']);
                }
                $model = new Lists();
                Db::startTrans();
                try {
                    $model->where(['id' => $data['id']])->update(['isdel' => 2]);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
                }
                return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
                break;
            default:
                return json(['code' => 1, 'data' => [], 'msg' => '操作类型错误']);
                break;
        }
    }

    public function lista_status2()
    {
        $data = input();
        switch ($data['status']) {
            case 'repeats':
                if (empty($data['id']) && count($data['id']) <= 0) {
                    return json(['code' => 1, 'data' => [], 'msg' => '请选择项目内容']);
                }
                $model = new Lists();
                Db::startTrans();
                try {
                    $model->where(['id' => $data['id']])->update(['repeats' => 2]);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
                }
                return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
                break;
            default:
                return json(['code' => 1, 'data' => [], 'msg' => '操作类型错误']);
                break;
        }
    }

    public function tags()
    {
        if ($this->request->isAjax()) {
            $model = new Tags();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['pe.status', '=', 1];
            if ($this->request->admin['id'] != 1) {
                $where[] = ['ta.type', 'in', $this->request->admin['groups']];
            }
            if (!empty($post['type'])) {
                $where[] = ['ta.type', '=', $post['type']];
            }
            $count = $model->alias('ta')->leftJoin('peizhi pe', 'pe.type = ta.type')->group('ta.type,ta.labelGroupId')->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->field('ta.*,pe.pinpai as type_name')->alias('ta')->leftJoin('peizhi pe', 'pe.type = ta.type')->group('ta.type,ta.labelGroupId')->where($where)->order("ta.type desc")->limit($limit)->page($page)->select();
            foreach ($list as $row) {
                // $row['type_name'] = (new Peizhi())->where(['type' => $row['type']])->value('pinpai') ?? '未知';
                $row['labellist'] = $model->where(['labelGroupId' => $row['labelGroupId'], 'type' => $row['type']])->select();
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            $peizhis = (new Peizhi());
            if ($this->request->admin['id'] != 1) {
                $peizhis = $peizhis->where(['type' => $this->request->admin['groups']]);
            }
            $peizhis = $peizhis->where('status', 1)->select();
            foreach ($peizhis as $peizhi) {
                //reids设置1小时更新一次
                $rdsnames = 'peizhitagsupdates' . $peizhi['id'];
                $rdspeizhi = Redis::get($rdsnames);
                if ($rdspeizhi) {
                    continue;
                }
                $url = "https://open.workec.com/v2/config/getLabelInfo";
                list($returnCode, $returnContent) = doGet($peizhi['cid'], $peizhi['appId'], $peizhi['appSecret'], $url, []);
                $rjson = json_decode($returnContent, true);
                Log::write($rjson, 'getdata');
                if (empty($rjson['data'])) {
                    $rjson['data'] = [];
                }
                Db::startTrans();
                try {
                    foreach ($rjson['data'] as $js) {
                        //查找是否已添加
                        foreach ($js['labelList'] as $sonsjs) {
                            $tags = (new Tags())->where(['type' => $peizhi['type'], 'labelId' => $sonsjs['labelId']])->find();
                            if (empty($tags)) {
                                (new Tags())->allowfield(true)->save([
                                    'type' => $peizhi['type'],
                                    'labelGroupId' => $js['labelGroupId'] ?? 0,
                                    'labelGroupName' => $js['labelGroupName'] ?? '',
                                    'labelId' => $sonsjs['labelId'] ?? 0,
                                    'labelName' => $sonsjs['labelName'] ?? '',
                                ]);
                            } else {
                                (new Tags())->where('id', $tags['id'])->update([
                                    'type' => $peizhi['type'],
                                    'labelGroupId' => $js['labelGroupId'] ?? 0,
                                    'labelGroupName' => $js['labelGroupName'] ?? '',
                                    'labelId' => $sonsjs['labelId'] ?? 0,
                                    'labelName' => $sonsjs['labelName'] ?? '',
                                ]);
                            }
                        }
                    }
                    Db::commit();
                    Redis::setex($rdsnames, 60, 60);
                } catch (\Exception $e) {
                    Db::rollback();
                    Log::write('----EC标签更新开始-----', 'getdata');
                    Log::write($e->getMessage(), 'getdata');
                    Log::write('----EC标签更新结束-----', 'getdata');
                }
            }
            return view(null, ['pinpai' => $peizhis]);
        }
    }

    public function tags_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'type' => 'require',
                'id' => 'require',
            ], [
                'type.require' => '品牌类型不能为空',
                'id.require' => 'ID不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' => $validate->getError()]);
            }
            if ($this->request->admin['id'] != 1 && !in_array($data['type'], $this->request->admin['groups'])) {
                return json(['code' => 1, 'msg' => '无品牌权限']);
            }
            $row = (new Tags())->where(['id' => $data['id']])->find();
            if (empty($row)) {
                return json(['code' => 1, 'msg' => '配置不存在']);
            }
            Db::startTrans();
            try {
                (new Tags())->where(['type' => $data['type'], 'labelGroupId' => $row['labelGroupId']])->update(['status' => 2]);
                if (!empty($data['values']) && is_array($data['values'])) {
                    (new Tags())->where(['id' => $data['values'], 'type' => $data['type']])->update(['status' => 1]);
                }
                Db::commit();
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => $e->getMessage()]);
                Db::rollback();
            }
            return json(['code' => 200, 'msg' => '操作成功']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Tags())->where('id', $id)->find();
            if ($row) {
                $row['labellist'] = (new Tags())->where(['labelGroupId' => $row['labelGroupId'], 'type' => $row['type']])->select() ?? [];
            }
            $pinpai = (new Peizhi())->where('status', 1)->select();
            $ptlaiyuan = config()['config']['laiyuan'] ?? [];
            return view('', ['row' => $row, 'pinpai' => $pinpai, 'ptlaiyuan' => $ptlaiyuan]);
        }
    }

    //商品导入
    public function import_batch_send()
    {
        $imageFilePath = $_SERVER['DOCUMENT_ROOT'] . '/excel2025/'; //图片本地存储的路径
        if (!file_exists($imageFilePath)) { //如果目录不存在则递归创建
            mkdir($imageFilePath, 777, true);
        }
        try {
            //上传excel文件
            $file = request()->file('file');
            $file_size = $_FILES['file']['size'];
            if ($file_size > 10 * 1024 * 1024) {
                $this->error('文件大小不能超过10M');
                exit();
            }
            //将文件保存到public/uploads目录下面
            $info = $file->validate(['ext' => 'xls,xlsx'])->move('./excel2025');
            $text = [];
            if ($info) {
                $extension = $info->getExtension();
                //获取上传到后台的文件名
                $fileName = $info->getSaveName();
                //获取文件路径
                $filePath = $_SERVER['DOCUMENT_ROOT'] . '/excel2025' . DIRECTORY_SEPARATOR . $fileName;
                // 引用PHPExcel类
                if ($extension == 'xlsx') {
                    $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
                } else if ($extension == 'xls') {
                    $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                } else {
                    return json(['status' => '1', 'mag' => '文件拓展出错']);
                }
                $objReader->setReadDataOnly(true);
                $obj_PHPExcel = $objReader->load($filePath, $encode = 'utf-8');  //加载文件内容,编码utf-8
                $objWorksheet = $obj_PHPExcel->getsheet(0);
                $data = $objWorksheet->toArray();
                if (count($data) <= 1) {
                    return json(['status' => '1', 'mag' => '数据必须超过一条']);
                }
                unset($data[0]);
                foreach ($data as $k => $row) {
                    //查找品牌是否存在
                    $peizhi = (new Peizhi())->where(['pinpai' => trim($row[0])])->value('type') ?? 0;
                    //判断品牌权限
                    if ($this->request->admin['id'] != 1 && !in_array($peizhi, $this->request->admin['groups'])) {
                        $text[] = '第' . ($k + 1) . '行失败跳过,无该品牌权限';
                        continue;
                    }
                    if (empty($peizhi)) {
                        $text[] = '第' . ($k + 1) . '行失败跳过,表单对应品牌不存在';
                        continue;
                    }
                    if (empty($row[1]) && empty($row[2])) {
                        $text[] = '第' . ($k + 1) . '行失败跳过,手机号或其他联系方式必须填写一个';
                        continue;
                    }
                    if (empty($row[3])) {
                        $text[] = '第' . ($k + 1) . '行失败跳过,请设置平台对应标签';
                        continue;
                    } else {
                        $tags = explode(',', $row[3]) ?? [];
                        if (count($tags) <= 0) {
                            $text[] = '第' . ($k + 1) . '行失败跳过,请填写标签并确认平台同步，多个请用' . ',' . '分开';
                            continue;
                        }
                        //查找标签
                        $tagcount = count($tags) - 1;
                        $tagslist = (new Tags())->where(['type' => $peizhi, 'labelName' => $tags[$tagcount]])->value('status') ?? 0;
                        if (empty($tagslist)) {
                            $text[] = '第' . ($k + 1) . '行失败跳过,未查找到对应标签，请确认平台同步或未设置空格';
                            continue;
                        }
                        //查找去重
                        $reother = [];
                        if (!empty($row[1])) {
                            $reother = (new Lists())->order('repeats asc')->where(['type' => $peizhi, 'phone' => trim($row[1]), 'isdel' => 1])->find();
                        }
                        if (empty($reother) && !empty($row[2])) {
                            $reother = (new Lists())->order('repeats asc')->where(['type' => $peizhi, 'othertel' => trim($row[2]), 'isdel' => 1])->find();
                        }
                        if (empty($reother)) {
                            $text[] = '第' . ($k + 1) . '行失败跳过,未查找到对应用户';
                            continue;
                        }
                        $res = (new Lists())->where('id', $reother['id'])->update(['youxiao' => $tagslist, 'yxtags' => $row[3], 'yxtext' => $row[4]]);
                        if ($res) {
                            $text[] = '第' . ($k + 1) . '行成功!';
                            continue;
                        } else {
                            $text[] = '第' . ($k + 1) . '行设置失败，请重试!';
                            continue;
                        }
                    }
                }
            } else {
                return json(['status' => '1', 'mag' => '文件过大或格式不正确导致上传失败-_-!']);
            }
            return json(['status' => '0', 'data' => $text]);
        } catch (\Exception $e) {
            throw $e;
        }
    }

    public function import_gsdxl()
    {
        $imageFilePath = $_SERVER['DOCUMENT_ROOT'] . '/gsdexcel/'; //图片本地存储的路径
        if (!file_exists($imageFilePath)) { //如果目录不存在则递归创建
            mkdir($imageFilePath, 777, true);
        }
        try {
            //上传excel文件
            $file = request()->file('file');
            $file_size = $_FILES['file']['size'];
            if ($file_size > 10 * 1024 * 1024) {
                $this->error('文件大小不能超过10M');
                exit();
            }
            //将文件保存到public/uploads目录下面
            $info = $file->validate(['ext' => 'xls,xlsx'])->move('./gsdexcel');
            $text = [];
            if ($info) {
                $extension = $info->getExtension();
                //获取上传到后台的文件名
                $fileName = $info->getSaveName();
                //获取文件路径
                $filePath = $_SERVER['DOCUMENT_ROOT'] . '/gsdexcel' . DIRECTORY_SEPARATOR . $fileName;
                // 引用PHPExcel类
                if ($extension == 'xlsx') {
                    $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
                } else if ($extension == 'xls') {
                    $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                } else {
                    return json(['status' => '1', 'mag' => '文件拓展出错']);
                }
                $objReader->setReadDataOnly(true);
                $obj_PHPExcel = $objReader->load($filePath, $encode = 'utf-8');  //加载文件内容,编码utf-8
                $objWorksheet = $obj_PHPExcel->getsheet(0);
                $data = $objWorksheet->toArray();
                if (count($data) <= 1) {
                    return json(['status' => '1', 'mag' => '数据必须超过一条']);
                }
                unset($data[0]);
                $saves = [];
                foreach ($data as $k => $row) {
                    try {
                        //查找品牌是否存在
                        $peizhi = (new Peizhi())->where(['pinpai' => trim($row[0])])->find() ?? 0;
                        if (empty($peizhi) || empty($peizhi['type'])) {
                            $text[] = '第' . ($k + 1) . '行失败跳过,表单对应品牌不存在';
                            continue;
                        }
                        //判断品牌权限
                        if ($this->request->admin['id'] != 1 && !in_array($peizhi['type'], $this->request->admin['groups'])) {
                            $text[] = '第' . ($k + 1) . '行失败跳过,无该品牌权限';
                            continue;
                        }
                        if (empty($row[4])) {
                            $datetime = time();
                        } else {
                            if (is_float($row[4])) {
                                $datetime = intval(($row[4] - 25569) * 3600 * 24);
                            } else {
                                $datetime = (int)(strtotime(($row[4] ?? '')));
                            }
                        }
                        if (empty($row[2]) && empty($row[3])) {
                            $text[] = '第' . ($k + 1) . '行失败跳过,手机号不能为空';
                            continue;
                        }
                        if (!empty($row[2]) && !preg_match("/^1[0-9]{10}$/", $row[2])) {
                            $text[] = '第' . ($k + 1) . '行失败跳过,手机号不正确';
                            continue;
                        }
                        //查重
                        if (!empty($row[2])) {
                            $lista = (new Lists())->where(['phone' => trim($row[2]), 'isdel' => 1, 'type' => $peizhi['type']])->find();
                            if (!empty($lista)) {
                                $text[] = '第' . ($k + 1) . '行失败跳过,手机号已存在';
                                continue;
                            }
                        }
                        if (!empty($row[3])) {
                            $lista = (new Lists())->where(['othertel' => trim($row[3]), 'isdel' => 1, 'type' => $peizhi['type']])->find();
                            if (!empty($lista)) {
                                $text[] = '第' . ($k + 1) . '行失败跳过,微信号已存在';
                                continue;
                            }
                        }
                        //查询归属地
                        $location = '';
                        try {
                            $getgsd = api_curl('https://api.asilu.com/phone/', ['phone' => $row[2]]);
                            if (!empty($getgsd['province']) && !empty($getgsd['city'])) {
                                $location = $getgsd['province'] . ' ' . $getgsd['city'];
                            }
                        } catch (\Exception $e) {
                            //throw $th;
                        }
                        $saves[] = [
                            'laiyuan' => $data['laiyuan'] ?? '未知',
                            'type' => $peizhi['type'] ?? 0,
                            'pinpai' =>  $peizhi['pinpai'] ?? '',
                            'name' =>  trim($row[1]) ?? "未命名",
                            'pingtai' => 'EXCEL导入',
                            'phone' =>  trim($row[2]) ?? "",
                            'othertel' =>  trim($row[3]) ?? "",
                            'address' => $location ?? "",
                            'created' =>  date('Y-m-d H:i:s'),
                            'createds' =>  date('Y-m-d H:i:s', $datetime),
                            'isexcel' => 2,
                            'allocation' => 1
                        ];
                    } catch (\Exception $e) {
                        $text[] = '第' . ($k + 1) . '行失败跳过,' . $e->getMessage();
                        continue;
                    }
                }
                if (count($saves) > 0) {
                    Db::startTrans();
                    try {
                        (new Lists())->allowfield(true)->saveAll($saves);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        Log::write($e->getMessage(), 'getdatalist');
                        $this->result([], 1, $e->getMessage());
                    }
                    $other = new \app\api\controller\Other();
                    App::invokeMethod([$other, 'testAddCustomer']);
                    $text[] = '导入完成';
                } else {
                    $text[] = '无数据导入';
                }
            } else {
                return json(['status' => '1', 'mag' => '文件过大或格式不正确导致上传失败-_-!']);
            }
            return json(['status' => '0', 'data' => $text]);
        } catch (\Exception $e) {
            throw $e;
        }
    }
}
